<?php

namespace App\Company\Repositories;

use Dcat\Admin\Form;
use Dcat\Admin\Grid\Model;
use Dcat\Admin\Show;


trait Tenant
{
    //租户数据处理前置条件
    /**
     * 查找数据
     * @param Model $model
     * @return array|\Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Support\Collection
     */
    public function get(Model $model)
    {
        $model->where('company_id', $this->getTenantId());
        return parent::get($model);
    }

    /**
     * 插入数据
     * @param Form $form
     * @return mixed
     */
    public function store(Form $form)
    {
        $form->updates(['company_id' => $this->getTenantId()]);
        return parent::store($form);
    }

    /**
     * 查询编辑页面数据.
     *
     * @param Form $form
     * @return array|\Illuminate\Contracts\Support\Arrayable
     */
    public function edit(Form $form)
    {
        $query = $this->newQuery();

        if ($this->isSoftDeletes) {
            $query->withTrashed();
        }

        $this->model = $query
            ->where('company_id', $this->getTenantId())
            ->with($this->getRelations())
            ->findOrFail($form->getKey(), $this->getFormColumns());

        return $this->model;
    }

    /**
     * 更新数据
     * @param Form $form
     * @return bool|null
     */
    public function update(Form $form)
    {
        if ($this->edit($form)->company_id != $this->getTenantId()) {
            return false;
        }
        return parent::update($form);
    }

    /**
     * 删除数据
     * @param Form $form
     * @param array $originalData
     * @return bool
     */
    public function delete(Form $form, array $originalData)
    {
        $models = $this->collection->keyBy($this->getKeyName());
        collect(explode(',', $form->getKey()))->filter()->each(function ($id) use ($form, $models) {
            $model = $models->where('tenant_id', $this->getTenantId())->get($id);
            if (!$model) {
                return;
            }
            $data = $model->toArray();
            if ($this->isSoftDeletes && $model->trashed()) {
                $form->deleteFiles($data, true);
                $model->forceDelete();
                return;
            } elseif (!$this->isSoftDeletes) {
                $form->deleteFiles($data);
            }
            $model->delete();
        });
        return true;
    }

    /**
     * 显示数据
     * @param Show $show
     * @return array
     */
    public function detail(Show $show)
    {
        $query = $this->newQuery();
        if ($this->isSoftDeletes) {
            $query->withTrashed();
        }
        $this->model = $query
            ->where('company_id', $this->getTenantId())
            ->with($this->getRelations())
            ->findOrFail($show->getKey(), $this->getDetailColumns());

        return $this->model;
    }

    /**
     * 获取租户ID
     * @return mixed
     */
    private function getTenantId(): int
    {
        return auth('company')->id()??0;
    }
}
